package com.game.springbootstart.filter;

import com.game.springbootstart.DTO.LoginUser;
import com.game.springbootstart.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority; // 添加此导入
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.game.springbootstart.utils.JwtUtil;
import com.game.springbootstart.entity.Admin;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String path = request.getRequestURI();
        // 跳过登录和登出接口

        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Token is null or not Bearer, skipping...");
            filterChain.doFilter(request, response);
            return;
        }

        token = token.substring(7);

        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            String userId = claims.getSubject();
            String redisKey = "tokens_" + userId;
            String storedToken = redisTemplate.opsForValue().get(redisKey);

            if (storedToken != null && storedToken.equals(token)) {
                String username = (String) claims.get("username");
                String role = (String) claims.get("role");
                List<String> permissions = new ArrayList<>();
                Object authoritiesRaw = claims.get("authorities");
                if (authoritiesRaw instanceof List) {
                    List<?> authList = (List<?>) authoritiesRaw;
                    for (Object auth : authList) {
                        if (auth instanceof String) {
                            permissions.add((String) auth);
                        } else if (auth instanceof Map) {
                            String authority = (String) ((Map<?, ?>) auth).get("authority");
                            if (authority != null) permissions.add(authority);
                        }
                    }
                }
                if (role != null && !permissions.contains(role)) {
                    permissions.add(role);
                }
                System.out.println("Extracted Permissions: " + permissions);

                Admin admin = new Admin();
                admin.setId(Long.valueOf(userId));
                admin.setUsername(username);
                admin.setRole(role);
                LoginUser user = new LoginUser(admin, permissions);
                System.out.println("User Authorities: " + user.getAuthorities());

                UsernamePasswordAuthenticationToken auth =
                        new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
                filterChain.doFilter(request, response);
            } else {
                System.out.println("Token not found or not the latest in Redis, invalid");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.getWriter().write("您的账号已在其他设备登录，请重新登录");
            }
        } catch (ExpiredJwtException e) {
            System.out.println("Token 过期: " + e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write("Token 已过期，请重新登录");
        } catch (Exception e) {
            System.out.println("Token 验证失败: " + e.getMessage());
            throw new RuntimeException("Token 验证失败: " + e.getMessage());
        }
    }
}